package user_service

import (
	"gorm.io/gorm"
	"log"
	ud "pear-admin-layui-go/app/sys/user/domain"
	fd "pear-admin-layui-go/framework/database"
)

func EditPage(id int64) ud.User {
	user := ud.User{Id: id}
	fd.Db.Select("username", "nick_name", "real_name", "sex", "phone", "email", "remark").First(&user)
	return user
}

func Enable(uer *ud.UserEnableRequest) *gorm.DB {
	return fd.Db.Model(ud.User{Id: uer.Id}).Select("enable", "update_time", "update_by",
		"update_name").Updates(ud.User{Enable: uer.Enable, UpdateTime: uer.UpdateTime, UpdateBy: uer.UpdateBy, UpdateName: uer.UpdateName})
}

func UserEdit(uer *ud.UserEditRequest) (tx *gorm.DB) {
	r := fd.Db.Model(ud.User{Id: uer.Id}).Updates(ud.User{Username: uer.Username, NickName: uer.NickName, RealName: uer.RealName,
		Sex: uer.Sex, Phone: uer.Phone, Email: uer.Email, Remark: uer.Email, UpdateTime: uer.UpdateTime, UpdateName: uer.UpdateName,
		UpdateBy: uer.UpdateBy})
	return r
}

func Save(uar *ud.UserSaveRequest) (*ud.User, error) {
	u := ud.User{
		Username:   uar.Username,
		NickName:   uar.NickName,
		RealName:   uar.RealName,
		Password:   "123456",
		Sex:        uar.Sex,
		Phone:      uar.Phone,
		Email:      uar.Email,
		Enable:     uar.Enable,
		Remark:     uar.Remark,
		DelFlag:    false,
		CreateTime: uar.CreateTime,
		CreateBy:   uar.CreateBy,
		CreateName: uar.CreateName,
	}
	r := fd.Db.Create(&u)
	return &u, r.Error
}

func Table(us ud.UserSearchRequest) ([]ud.User, int64) {
	var count int64
	db := fd.Db.Model(ud.User{}).Where("del_flag = false")
	if us.Username != "" {
		db.Where("username like ?", "%"+us.Username+"%")
	}
	db.Count(&count)
	var users []ud.User
	db.Select("id", "username", "nick_name", "real_name", "sex", "phone", "enable", "email", "login", "remark", "create_time",
		"create_name", "update_time", "update_name").Limit(us.Limit).Offset((us.Page - 1) * us.Limit).Find(&users)
	return users, count
}

func Login(u ud.LoginRequest) ud.User {
	var dbUser ud.User
	fd.Db.First(&dbUser, "username = ? AND password = ?", u.Username, u.Password)
	log.Println(dbUser)
	return dbUser
}
